import Config from './config.js'
// import JSEncrypt from 'jsencrypt'
import Http from './http.js'

export default {
	/**
	 * 页面跳转
	 * @param {string} to 跳转链接 /pages/idnex/index
	 * @param {Object} param 参数 {key : value, ...}
	 * @param {string} mode 模式 
	 */
	redirectTo(to, param, mode) {
		let url = to;
		let tabbarList = ['/pages/index/index','/pages/warning/warning','/pages/record/record']
		for (let i = 0; i < tabbarList.length; i++) {
			if (to.indexOf(tabbarList[i]) != -1) {
				uni.switchTab({
					url: url
				})
				return;
			}
		}
		if (param != undefined) {
			Object.keys(param).forEach(function(key) {
				if (url.indexOf('?') != -1) {
					url += "&" + key + "=" + param[key];
				} else {
					url += "?" + key + "=" + param[key];
				}
			});
		}
		switch (mode) {
			case 'tabbar':
				// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
				uni.switchTab({
					url: url
				})
				break;
			case 'redirectTo':
				// 关闭当前页面，跳转到应用内的某个页面。
				uni.redirectTo({
					url: url
				});
				break;
			case 'reLaunch':
				// 关闭所有页面，打开到应用内的某个页面。
				uni.reLaunch({
					url: url
				});
				break;
			case 'navigateBack':
				// 关闭当前页面，返回delta层的某个页面。
				uni.navigateBack({
					delta: delta
				});
				break;
			default:
				// 保留当前页面，跳转到应用内的某个页面
				uni.navigateTo({
					url: url
				});
		}
	},
	goBack(backUrl = '/pages/index/index/index') {
		if (getCurrentPages().length == 1) {
			this.redirectTo(backUrl);
		} else {
			uni.navigateBack();
		}
	},
	// 【将一个数组,分割为指定个数的新数组】
	divisionArrFn(arr, num) {
	  // arr 必传 Array 需要分割数组
	  // num 必传 Number 每组的个数
	  // 注：也可以用于分割字符串
	  var newArr = [];
	  for (var i = 0, l = arr.length; i < l / num; i++) {
	    var a = arr.slice(num * i, num * (i + 1));
	    newArr.push(a);
	  }
	  return newArr;
	},
	// 距离单位换算
	unitDeal(dis){
		return Number(dis).toFixed(2)+'km'
		// if(dis<1000){
		// 	return Number(dis).toFixed(2)+'m'
		// }else{
		// 	return (dis/1000).toFixed(2)+'km'
		// }
	},
	// 获取地址名称
	getAddress(location,callback){
		uni.request({
			url: 'https://apis.map.qq.com/ws/geocoder/v1',
			data: {
				key: Config.mpKey,
				output: 'json',
				location: location.latitude + ',' + location.longitude,
			},
			success: (res => {
				console.log(res)
				if (res.data.status == 0) {
					callback(res.data.result)
				}else{
					callback()
				}
			})
		})
	},
	/**
	 * 图片路径转换
	 * @param {String} img_path 图片地址
	 * @param {Object} params 参数，针对商品、相册里面的图片区分大中小，size: big、mid、small
	 */
	img(img_path, params) {
		var path = "";
		if (img_path && img_path != undefined && img_path != "") {
			if (params && img_path != this.getDefaultImage().default_goods_img) {
				// 过滤默认图
				let arr = img_path.split(".");
				let suffix = arr[arr.length - 1];
				arr.pop();
				arr[arr.length - 1] = arr[arr.length - 1] + "_" + params.size.toUpperCase();
				arr.push(suffix);
				img_path = arr.join(".");
			}
			if (img_path.indexOf("http://") == -1 && img_path.indexOf("https://") == -1) {
				let imgDomin = Config.imgDomain.split('//')[1]
				if(img_path.indexOf(imgDomin) == -1){
					console.log('111111111111')
					path = Config.imgDomain + img_path;
				}else{
					console.log('2222222222')
					path = 'https:' + img_path;
				}
			} else {
				path = img_path;
			}
			// 处理商品助手的图片路径
			path = path.replace("addons/NsGoodsAssist/", "").replace("shop/goods/", "");
		}
		return path;
	},
	// 【 调用'获取图片信息'微信接口(在往画布上画图片时需要) 】
	getAllImgInfoFn(urlArr, success, that) {
	  // --- urlArr 必传 Array 需要获取的'图片链接'数组 默认值:[]
	  // --- success 必传 function 全部获取完成时,回调的函数 默认值:--
	  let newImgArr = []; // 处理后的新图片信息数组
	  // 准备和补充数组
	  for (let url of urlArr) {
	    let newImgObj = {
	      oldUlr: url, // 原链接
	      newUrl: "", // 新链接
	      getState: 0, // 获取结果 0未开始 1成功 2失败
	      endBool: false // 获取是否结束
	    };
	    newImgArr.push(newImgObj);
	    console.log(newImgObj);
	  }
	
	  // 循环获取'图片信息'
	  newImgArr.forEach((newImg, index) => {
	    console.log(newImg, index, "res------开始转换-------------");
	    uni.getImageInfo({
	      src: newImg.oldUlr,
	      success: function (res) {
	        console.log(res, index, "res------转换成功-------------");
	        newImg.newUrl = res.path;
	        newImg.getState = 1;
	        newImg.endBool = true;
	        testLoadEndFn(newImgArr, that);
	      },
	      fail: function (err) {
		   console.log(err, index, "err------转换失败-------------");
	        newImg.newUrl = newImg.oldUlr;
	        newImg.getState = 2;
	        newImg.endBool = true;
	        testLoadEndFn(newImgArr, that);
	      }
	    })
	  });
	  // 检查是否加载完毕
	  function testLoadEndFn(arr, that) {
	    let loadEndBool = true;
	    for (const each of arr) {
	      if (!each.endBool) loadEndBool = false;
	    }
		console.log(arr,'arr')
	    if (loadEndBool) {
	      success(arr, that);
	    }else{
			uni.hideLoading()
			that.$util.showToast({title:'图片转换失败'})
		}
	  }
	},
	/**
	 * 时间戳转日期格式
	 * @param {Object} timeStamp
	 */
	timeStampTurnTime(timeStamp, type = "",type1="") {
		if (timeStamp != undefined && timeStamp != "" && timeStamp > 0) {
			var date = new Date();
			date.setTime(timeStamp * 1000);
			var y = date.getFullYear();
			var m = date.getMonth() + 1;
			m = m < 10 ? ('0' + m) : m;
			var d = date.getDate();
			d = d < 10 ? ('0' + d) : d;
			var h = date.getHours();
			h = h < 10 ? ('0' + h) : h;
			var minute = date.getMinutes();
			var second = date.getSeconds();
			minute = minute < 10 ? ('0' + minute) : minute;
			second = second < 10 ? ('0' + second) : second;
			if (type) {
				return y + '-' + m + '-' + d;
			} else {
				if(type1=='1'){
					return  h + ':' + minute;
				}else if(type1=='min'){
					return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
				}
				return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
			}
		} else {
			return "";
		}
	},
	/**
	 * 日期格式转时间戳
	 * @param {Object} timeStamp
	 */
	timeTurnTimeStamp(string) {
		var f = string.split(' ', 2);
		var d = (f[0] ? f[0] : '').split('-', 3);
		var t = (f[1] ? f[1] : '').split(':', 3);
		return (new Date(
			parseInt(d[0], 10) || null,
			(parseInt(d[1], 10) || 1) - 1,
			parseInt(d[2], 10) || null,
			parseInt(t[0], 10) || null,
			parseInt(t[1], 10) || null,
			parseInt(t[2], 10) || null
		)).getTime();
	},
	/**
	 * 倒计时
	 * @param {Object} seconds 秒
	 */
	countDown(seconds) {
		let [day, hour, minute, second] = [0, 0, 0, 0]
		if (seconds > 0) {
			day = Math.floor(seconds / (60 * 60 * 24))
			hour = Math.floor(seconds / (60 * 60)) - (day * 24)
			minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
			second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
		}
		if (day < 10) {
			day = '0' + day
		}
		if (hour < 10) {
			hour = '0' + hour
		}
		if (minute < 10) {
			minute = '0' + minute
		}
		if (second < 10) {
			second = '0' + second
		}
		return {
			d: day,
			h: hour,
			i: minute,
			s: second
		};
	},
	/**
	 * 数值去重
	 * @param {Array} arr 数组
	 * @param {string} field 字段
	 */
	unique(arr, field) {
		const res = new Map();
		return arr.filter((a) => !res.has(a[field]) && res.set(a[field], 1));
	},
	/**
	 * 判断值是否在数组中
	 * @param {Object} elem
	 * @param {Object} arr
	 * @param {Object} i
	 */
	inArray: function(elem, arr) {
		return arr == null ? -1 : arr.indexOf(elem);
	},
	/**
	 * 获取某天日期
	 * @param {Object} day
	 */
	getDay: function(day) {
		var today = new Date();
		var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
		today.setTime(targetday_milliseconds);

		const doHandleMonth = function(month) {
			var m = month;
			if (month.toString().length == 1) {
				m = "0" + month;
			}
			return m
		}

		var tYear = today.getFullYear();
		var tMonth = today.getMonth();
		var tDate = today.getDate();
		var tWeek = today.getDay();
		var time = parseInt(today.getTime() / 1000);
		tMonth = doHandleMonth(tMonth + 1);
		tDate = doHandleMonth(tDate);

		const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
		return {
			't': time,
			'y': tYear,
			'm': tMonth,
			'd': tDate,
			'w': week[tWeek]
		};
	},
	dateFormat: function(date, type) {
		let year = date.split('-')[0]
		let month = date.split('-')[1]
		let day = date.split('-')[2]
		if (type == 'year') {
			return year + '年'
		} else if (type == 'month') {
			return month + '月'
		} else if (type == 'ymDay') {
			return year + '年' + month + '月' + day + '日'
		} else {
			return year + '年' + month + '月'
		}
	},
	/**
	 * 图片选择加上传
	 * @param number num
	 * @param {Object} params
	 * @param {Object} callback
	 * @param string url
	 * return array
	 */
	upload: function(num, params, callback, url) {
		// #ifdef H5
		var app_type = this.isWeiXin() ? 'wechat' : 'h5';
		var app_type_name = this.isWeiXin() ? '微信公众号' : 'H5';
		// #endif

		// #ifdef MP-WEIXIN
		var app_type = 'weapp';
		var app_type_name = '微信小程序';
		// #endif

		// #ifdef MP-ALIPAY
		var app_type = 'aliapp';
		var app_type_name = '支付宝小程序';
		// #endif

		// #ifdef MP-BAIDU
		var app_type = 'baiduapp';
		var app_type_name = '百度小程序';
		// #endif

		// #ifdef MP-TOUTIAO
		var app_type = 'MP-TOUTIAO';
		var app_type_name = '头条小程序';
		// #endif

		// #ifdef MP-QQ
		var app_type = 'MP-QQ';
		var app_type_name = 'QQ小程序';
		// #endif
		var data = {
			// token: uni.getStorageSync('token'),
			// app_type: app_type,
			// app_type_name: app_type_name
		}
		data = Object.assign(data, params);

		// 请求参数加密
		// if (Config.apiSecurity) {
		// 	let jsencrypt = new JSEncrypt();
		// 	jsencrypt.setPublicKey(Config.publicKey);
		// 	let encrypt = encodeURIComponent(jsencrypt.encryptLong(JSON.stringify(data)));
		// 	data = {
		// 		encrypt
		// 	};
		// }
		var imgs_num = num;
		var _self = this;
		uni.chooseImage({
			count: imgs_num,
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册或者拍照
			success: async function(res) {
				const tempFilePaths = res.tempFilePaths;

				var _data = data;
				var imgs = [];
				for (var i = 0; i < tempFilePaths.length; i++) {
					var path = await _self.upload_file_server(tempFilePaths[i], _data, params.path,
					url);
					imgs.push(path);
				}
				typeof callback == 'function' && callback(imgs);
			}
		});
	},
	//上传
	upload_file_server(tempFilePath, data, path, url = "") {
		let _this=this;
		if (url) {
			var uploadUrl = Config.baseImgUrl + url
		} else {
			var uploadUrl = Config.baseImgUrl + '/api/admin/v1/storage/upload/new'
		}
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: uploadUrl,
				filePath: tempFilePath,
				name: 'file',
				formData: data,
				success: function(res) {
					console.log(res,'res=====uploadFile')
					if(res.statusCode==200){
						var resp = JSON.parse(res.data);
						if (resp.code ==200) {
							resolve(resp.response);
						} else {
							_this.showToast({title:resp.msg||'上传失败，请重新上传'})
							reject("error");
						}
					}else{
						_this.showToast({title:'接口请求失败'})
						reject("error");
					}
				},
				fail:err=>{
					reject()
					_this.showToast({title:'请求失败'})
				}
			});

		});

	},
	/**
	 * 复制
	 * @param {Object} message
	 * @param {Object} callback
	 */
	copy(value, callback) {
		// #ifdef H5
		var oInput = document.createElement('input'); //创建一个隐藏input（重要！）
		oInput.value = value; //赋值
		oInput.setAttribute("readonly", "readonly");
		document.body.appendChild(oInput);
		oInput.select(); // 选择对象
		document.execCommand("Copy"); // 执行浏览器复制命令
		oInput.className = 'oInput';
		oInput.style.display = 'none';
		uni.hideKeyboard();
		this.showToast({
			title: '复制成功'
		});

		typeof callback == 'function' && callback();
		// #endif

		// #ifdef MP || APP-PLUS
		uni.setClipboardData({
			data: value,
			success: () => {
				typeof callback == 'function' && callback();
			}
		});
		// #endif
	},
	/**
	 * 显示消息提示框
	 *  @param {Object} params 参数
	 */
	showToast(params = {}) {
		params.title = params.title || "";
		params.icon = params.icon || "none";
		// params.position = params.position || 'bottom';
		params.duration = params.duration || 1500;
		uni.showToast(params);
		if (params.success) params.success();
	},
	//判断安卓还是iOS
	isAndroid() {
		let platform = uni.getSystemInfoSync().platform
		if (platform == 'ios') {
			return false;
		} else if (platform == 'android') {
			return true;
		}
	},
	/**
	 * 深度拷贝对象
	 * @param {Object} obj
	 */
	deepClone(obj) {
		const isObject = function(obj) {
			return typeof obj == 'object';
		}
		if (!isObject(obj)) {
			throw new Error('obj 不是一个对象！')
		}
		//判断传进来的是对象还是数组
		let isArray = Array.isArray(obj)
		let cloneObj = isArray ? [] : {}
		//通过for...in来拷贝
		for (let key in obj) {
			cloneObj[key] = isObject(obj[key]) ? this.deepClone(obj[key]) : obj[key]
		}
		return cloneObj
	},
	/**
	 * 获取默认图
	 * @param {Object} link
	 */
	getDefaultImage() {
		let defaultImg = uni.getStorageSync('default_img');
		if (defaultImg) {
			defaultImg = JSON.parse(defaultImg);
			defaultImg.default_goods_img = this.img(defaultImg.default_goods_img);
			defaultImg.default_headimg = this.img(defaultImg.default_headimg);
			defaultImg.default_storeimg = this.img(defaultImg.default_storeimg);
			return defaultImg;
		} else {
			return {
				default_goods_img: '',
				default_Pets_img: '',
				default_headimg: '',
				default_storeimg: ''
			};
		}
	},
	/**
	 * 判断手机是否为iphoneX及以上系列
	 */
	uniappIsIPhoneX() {
		let isIphoneX = false;
		let systemInfo = uni.getSystemInfoSync();
		// #ifdef MP
		if (systemInfo.safeArea.top > 20 && systemInfo.model.search('iPhone') != -1) {
			isIphoneX = true;
		}
		// #endif

		// #ifdef H5
		var u = navigator.userAgent;
		var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

		if (isIOS) {
			if (systemInfo.screenWidth == 375 && systemInfo.screenHeight == 812 && systemInfo.pixelRatio == 3) {
				isIphoneX = true;
			} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 3) {
				isIphoneX = true;
			} else if (systemInfo.screenWidth == 414 && systemInfo.screenHeight == 896 && systemInfo.pixelRatio == 2) {
				isIphoneX = true;
			}
		}
		// #endif
		return isIphoneX;
	},

	/**
	 * 判断当前页面栈是否存在，如果存在，则返回该页面栈，否则跳转到该页面
	 */
	jumpPage(url) {
		let jump = true;
		let arr = getCurrentPages().reverse();
		for (let i = 0; i < arr.length; i++) {
			if (url.indexOf(arr[i].route) != -1) {
				jump = false;
				uni.navigateBack({
					delta: i
				});
				break;
			}
		}
		if (jump) {
			this.diyRedirectTo(url);
		}
	},
	// 设置保留几位小数
	numberFixed(e, f) {
		if (!f) {
			f = 0;
		}
		return Number(e).toFixed(f);
	},
	/**
	 * 获取url参数
	 */
	getUrlCode(callback) {
		var url = location.search;
		var theRequest = new Object();
		if (url.indexOf('?') != -1) {
			var str = url.substr(1);
			var strs = str.split('&');
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
			}
		}
		typeof callback == 'function' && callback(theRequest);
	},

	formateDate: function(datetime, type) {
		var year = datetime.getFullYear(),
			month = ("0" + (datetime.getMonth() + 1)).slice(-2),
			date = ("0" + datetime.getDate()).slice(-2),
			hour = ("0" + datetime.getHours()).slice(-2),
			minute = ("0" + datetime.getMinutes()).slice(-2),
			second = ("0" + datetime.getSeconds()).slice(-2);
		if (type === "Y-M-D h:min:s") {
			var result = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
		} else if (type === "Y-M-D") {
			var result = year + "-" + month + "-" + date;
		}
		if (type === "h:min:s") {
			var result = hour + ":" + minute + ":" + second;
		}
		return result;
	},

	getTimeFormat: function(time) {
		var hour = ('0' + parseInt(time / 60)).slice(-2),
			minute = ("0" + time % 60).slice(-2)
		var result = hour + ":" + minute
		return result;
	},

	// 日期数组
	getDateArr: function(days) {
		if (days == '' || days == null || days == undefined || typeof days != "number") {
			return false;
		}
		var res = []
		var today = new Date().getTime()
		for (var i = 0; i < days; i++) {
			var _day = new Date(today + 86400000 * i),
				year = _day.getFullYear(),
				month = (_day.getMonth() + 1),
				day = _day.getDate();
			month < 10 ? '0' + month : month;
			day < 10 ? '0' + day : day;
			res.push({
				date: year + '-' + month + '-' + day,
				dateStr: year + '年' + month + '日' + day + '日',
			});
		}
		return res;
	}
}
